//
//  SCNBaseViewController.swift
//  ShoucainuSwift
//
//  Created by 王家旭 on 2017/2/6.
//  Copyright © 2017年 Riluee. All rights reserved.
//

import UIKit


class SCNBaseViewController: UIViewController {
   
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = SCNConstants.tableViewBackgroundColor

        
        let attributes: [String : Any] = [
            NSFontAttributeName : UIFont(name: "Helvetica", size: 22.0)!,
            NSForegroundColorAttributeName : UIColor.white
            ]
        
        self.navigationController?.navigationBar.titleTextAttributes = attributes
        self.navigationController?.navigationBar.tintColor = .white
        self.navigationController?.navigationBar.barTintColor = SCNConstants.rootBackgroundColor
        
        if let count = self.navigationController?.childViewControllers.count, count > 1 {
            configurationBackBar()
        }
        

        
    }
    // 替换掉系统的push方法
    func scnPushViewController(_ viewController: UIViewController) {
        
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(viewController, animated: true)
        
        
        /*
         这里发现一个问题：
         在 hidesBottomBarWhenPushed = true 设置之后
         如果当前控制器在导航栈的第二层，在 pop 回来 tabbar 没有显示出来（这样就需要在push 后加上 hidesBottomBarWhenPushed = false ）来解决这个问题
         可是如果当前控制器在导航栈的第三层，在 pop 回来第二层的时候没有显示，而回来第一层就显示出来了
         这里做一些逻辑控制
         
         */
        let navViewController = self.navigationController
        let rootViewController = navViewController?.viewControllers[0]
        
        if self.isMember(of: (rootViewController?.classForCoder)!) {
        
            self.hidesBottomBarWhenPushed = false
        }

    }
    
    func configurationBackBar() {
        // 返回按钮
        let backButton = UIButton(type: .custom)
        
        // 给按钮设置返回箭头图片
        backButton.setBackgroundImage(UIImage(named: "navWhiteBar_Back"), for: .normal)
        backButton.setBackgroundImage(UIImage(named: "navWhiteBar_Back"), for: .highlighted)
        // 设置frame
        backButton.frame = CGRect(x: 200, y: 13, width: 18, height: 18)
        backButton.addTarget(self, action: #selector(back), for: .touchUpInside)
        
        // 自定义导航栏的UIBarButtonItem类型的按钮
        let backView = UIBarButtonItem(customView: backButton)
        
        // 重要方法，用来调整自定义返回view距离左边的距离
        let barButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        barButtonItem.width = -5
        
        // 返回按钮设置成功
        navigationItem.leftBarButtonItems = [barButtonItem, backView]
        
    }

    deinit {
        printLog("release -> \(self.classForCoder)")
    }

}

extension SCNBaseViewController {
    // MARK: ACTION
    func back() {
        self.navigationController?.popViewController(animated: true)
    }
}
